package client.comm.commlib.comm_ui

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import client.comm.commlib.R
import client.comm.commlib.databinding.ActivitySelectphotoBinding
import client.comm.commlib.databinding.ActivityWebBinding
import client.comm.commlib.widget.EmptyLayout


class WebActivity : AppCompatActivity() {

    fun getLayout(): Int {
        return R.layout.activity_web
    }

    var title: String? = ""
    var url: String? = ""

    lateinit var binding: ActivityWebBinding


//    val binding by lazy {
//        ActivityWebBinding.inflate(LayoutInflater.from(this))
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(binding.root)
//        initView()

        if (getLayout() > 0) {
            binding = DataBindingUtil.setContentView(this, getLayout())
            binding.lifecycleOwner = this
        }
        initView()
        lifecycleScope.launchWhenCreated { }

    }

    fun initView() {
        binding.event = this
        url = intent.getStringExtra("adInfo")
        title = intent.getStringExtra("title")
        binding.title = (title)

        val mWebSettings = binding.wvShow.settings
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setBuiltInZoomControls(false)
        mWebSettings.setLightTouchEnabled(true)
        mWebSettings.setSupportZoom(false)
        binding.wvShow.isHapticFeedbackEnabled = false
        url?.let {
            binding.wvShow.loadUrl(url!!)
        }
        binding.wvShow.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                url?.let {
                    view.loadUrl(url!!)
                }
                return true
            }

            @RequiresApi(Build.VERSION_CODES.KITKAT)
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.emptyLayout.visibility = View.GONE
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR

            }
        })
    }

    override fun onDestroy() {
        binding.wvShow.destroy()
        super.onDestroy()
    }
}